import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../views/Home.vue')
    },
    {
      path: '/news',
      name: 'NewsList',
      component: () => import('../views/NewsList.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/news/:id',
      name: 'NewsDetail',
      component: () => import('../views/NewsDetail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/admin',
      name: 'Admin',
      component: () => import('../views/Admin.vue'),
      meta: { requiresAuth: true, requiresAdmin: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.requiresAdmin) {
    // 检查是否是管理员
    try {
      const tokenData = JSON.parse(atob(token.split('.')[1]))
      if (tokenData.role === 'admin') {
        next()
      } else {
        next('/news')
      }
    } catch (error) {
      console.error('Token parsing error:', error)
      next('/login')
    }
  } else {
    next()
  }
})

export default router 